package com.glorysoft.tonglingxjpda.ui.order.viewmodel

import android.os.Handler
import android.os.Looper
import androidx.databinding.ObservableArrayList
import androidx.lifecycle.MutableLiveData
import com.glorysoft.hlgdpda.entity.ui.CallObserveBean
import com.glorysoft.tonglingxjpda.entity.ui.ToastMessageBean
import com.glorysoft.tonglingxjpda.R
import com.glorysoft.tonglingxjpda.base.BaseViewModel
import com.glorysoft.tonglingxjpda.entity.BomEntity
import com.glorysoft.tonglingxjpda.entity.CustomEntity
import com.glorysoft.tonglingxjpda.entity.DefectEntity
import com.glorysoft.tonglingxjpda.entity.OrderListEntity
import com.glorysoft.tonglingxjpda.model.TaskRepository
import com.glorysoft.tonglingxjpda.utils.FileUtils
import com.glorysoft.tonglingxjpda.utils.SmbFileUtils
import com.google.gson.Gson
import com.google.gson.JsonObject
import com.google.gson.JsonParser
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DateUtils
import jcifs.smb.SmbFile
import me.tatarka.bindingcollectionadapter2.BR
import me.tatarka.bindingcollectionadapter2.ItemBinding
import java.io.File
import kotlin.concurrent.thread

/**
 * FileName: OrderMangerViewModel
 * Author: XJH
 * Date: 2021/7/16 17:43
 * Description:
 * History:
 */
class OrderMangerViewModel : BaseViewModel() {
    var orderEntity = MutableLiveData<OrderListEntity>()
    private val handler = Handler(Looper.getMainLooper())
    var customList = arrayListOf<String>()
    var bomList = arrayListOf<String>()
    var bomEntity = CustomEntity()
    private val orderRepository = TaskRepository()
    private val onProdItemClickListener = object : OnItemClickListener {
        override fun onItemClick(item: Any) {
//            var entity = item as BomEntity
//            if (entity.RESERVED7 == "Spilt") {
//                defUI.callObserve.value = CallObserveBean(0, item)
//            } else {
//                defUI.toastEvent.value = ToastMessageBean("当前项不要刻印号", false)
//            }
            defUI.callObserve.value = CallObserveBean(0, item)
        }

        override fun onAddClick(item: Any) {
            val entity = item as BomEntity
            try {
                val i = item.MAINQTY.toInt() + 1
                item.MAINQTY = i.toString()
            }catch (e : Exception){
                item.MAINQTY = "1"
            }


        }

        override fun onReduce(item: Any) {
            val entity = item as BomEntity
            try {
                if (item.MAINQTY == "0" || item.MAINQTY.isEmpty()){
                    item.MAINQTY = "0"
                    return
                }else{
                    val i = item.MAINQTY.toInt() - 1
                    item.MAINQTY = i.toString()
                }
            }catch (e : Exception){
                item.MAINQTY = "0"
            }
        }

    }

    private val onIconItemListener = object : OnItemClickListener {
        override fun onItemClick(item: Any) {
            defUI.callObserve.value = CallObserveBean(200, item)
        }

        override fun onAddClick(item: Any) {

        }

        override fun onReduce(item: Any) {

        }

    }
    var prodItems = ObservableArrayList<BomEntity>()
    var prodBinding =
        ItemBinding.of<BomEntity>(BR.prodItem, R.layout.item_prod_list)
            .bindExtra(BR.onProdItemListener, onProdItemClickListener).bindExtra(BR.onIconItemListener,onIconItemListener)

    fun init(docID: String) {
        val entity = OrderListEntity()
        entity.PO = OrderListEntity.OrderInfoEntity("CREATED")
        if (docID.isEmpty()) {
            orderEntity.value = entity
            defUI.callObserve.value = CallObserveBean(3, "FAIL")
        } else {
            val map = JsonObject()
            map.addProperty("ACTIONTYPE", "POINFO")
            map.addProperty("DOCID", docID)
            launchOnlyResult({
                val orderInfoByDocID = orderRepository.getOrderInfoByDocID(map)
                when (orderInfoByDocID.PO.RESERVED5) {
                    "Urgent" -> orderInfoByDocID.PO.RESERVED5 = "是"
                    "UnUrgent" -> orderInfoByDocID.PO.RESERVED5 = "否"
//                    "Spilt" ->orderInfoByDocID.PO.RESERVED5 = "分批"
//                    "UnSpilt" ->orderInfoByDocID.PO.RESERVED5 = "不分批"
                }
//                when (orderInfoByDocID.PO.RESERVED2) {
//                    "NonCopper" -> orderInfoByDocID.PO.RESERVED2 = "铜"
//                    "UnNonCopper" -> orderInfoByDocID.PO.RESERVED2 = "非铜"
//                }
                orderEntity.value = orderInfoByDocID

                savePic(orderInfoByDocID.BOM)
                defUI.callObserve.value = CallObserveBean(3, "FAIL")
            })
        }


    }

    private fun savePic(bom: List<BomEntity>) {
        defUI.callObserve.value = CallObserveBean(1, "FAIL")
        thread {
            if (bom.isNotEmpty()) {
                bom.forEach {
                    if (it.PIC.isNotEmpty()) {
                        if (SmbFileUtils.smbGet(
                                it.PIC,
                                FileUtils.getLocalPathAndFileName(getApplication())
                            )
                        ) {
                            val remoteFile = SmbFile(it.PIC)
                            val fileName = remoteFile.name
                            it.localPath =
                                FileUtils.getLocalPathAndFileName(getApplication()) + File.separator + fileName
                        }
                    }
                }
            }

            handler.post {
                prodItems.clear()
                prodItems.addAll(bom)
                defUI.callObserve.value = CallObserveBean(2, "FAIL")
            }
        }

    }

    fun getCustom() {
        val map = JsonObject()
        map.addProperty("ACTIONTYPE", "CUSTOMER")
        launchOnlyResult({
            val custom = orderRepository.getCustom(map)
            for (customInfoEntity in custom.CUSTOMER) {
                customList.add(customInfoEntity.NAME + "#" + customInfoEntity.DESCRIPTION)
            }
        })
    }

    fun getBom(custom: String) {
        val map = JsonObject()
        map.addProperty("ACTIONTYPE", "BOM")
        map.addProperty("CUSTOMERNAME", custom)
        launchOnlyResult({
            bomEntity = orderRepository.getBom(map)
            bomList.clear()
            for (bomEntity in bomEntity.BOM) {
                bomList.add(bomEntity.NAME + "#" + bomEntity.DESCRIPTION)
            }

        })
    }

    fun getProdList(bom: String) {
        for (bomEntity in bomEntity.BOM) {
            if (bomEntity.NAME == bom) {
                savePic(bomEntity.BOMLINE)
//                prodItems.addAll(bomEntity.BOMLINE)
            }
        }
    }

    fun save(action: String) {
        if (orderEntity.value!!.PO.DOCSTATUS != "CREATED") {
            defUI.toastEvent.value = ToastMessageBean("当前订单状态不允许保存", false)
            return
        }

        val map = JsonObject()
        map.addProperty("ACTIONTYPE", action)
        map.addProperty("docId", orderEntity.value!!.PO.DOCID)
        when (orderEntity.value!!.PO.RESERVED5) {
            "是" -> orderEntity.value!!.PO.RESERVED5 = "Urgent"
            "否" -> orderEntity.value!!.PO.RESERVED5 = "UnUrgent"
        }
        when (orderEntity.value!!.PO.RESERVED2) {
            "铜" -> orderEntity.value!!.PO.RESERVED2 = "NonCopper"
            "非铜" -> orderEntity.value!!.PO.RESERVED2 = "UnNonCopper"
        }
        if (orderEntity.value!!.PO.PLANENDDATE == null || orderEntity.value!!.PO.PLANENDDATE!!.isEmpty()) {
            orderEntity.value!!.PO.PLANENDDATE = null
        }

//        if (orderEntity.value!!.PO.DESCRIPTION.contains("\"")){
//            orderEntity.value!!.PO.DESCRIPTION = orderEntity.value!!.PO.DESCRIPTION.replace("\"","\\\"")
//        }
        orderEntity.value!!.PO.CREATED = FreeApi_DateUtils.getNowStringDate("yyyy/MM/dd HH:mm:ss")

        if (orderEntity.value!!.PO.PLANSTARTDATE.isEmpty()) {
            orderEntity.value!!.PO.PLANSTARTDATE =FreeApi_DateUtils.getNowStringDate("yyyy/MM/dd HH:mm:ss")
        }
        map.add("PO", JsonParser().parse(Gson().toJson(orderEntity.value!!.PO)).asJsonObject)
        map.add("MMBom", JsonParser().parse(Gson().toJson(prodItems)).asJsonArray)
        launchOnlyResult({
            orderRepository.savePo(map)
            defUI.toastEvent.value = ToastMessageBean("保存成功", true)
            defUI.startActivity.call()
        })

    }

    interface OnItemClickListener {
        fun onItemClick(item: Any)
        fun onAddClick(item: Any)
        fun onReduce(item: Any)
    }
}